<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/doc/src/qt4-sql.qdoc -->
<head>
  <title>Qt 4.3: The Qt 4 Database GUI Layer</title>
  <link rel="prev" href="qt4-accessibility.html" />
  <link rel="contents" href="qt4-intro.html" />
  <link rel="next" href="qt4-network.html" />
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><p>
[Previous: <a href="qt4-accessibility.html">Cross-Platform Accessibility Support in Qt 4</a>]
[<a href="qt4-intro.html">Home</a>]
[Next: <a href="qt4-network.html">The Network Module in Qt 4</a>]
</p>
<h1 align="center">The Qt 4 Database GUI Layer<br /><small></small></h1>
<p>The GUI layer of the SQL module in Qt 4 has been entirely redesigned to work with <a href="qt4-interview.html">Interview</a> (Qt's new model/view classes). It consists of three model classes (<a href="qsqlquerymodel.html">QSqlQueryModel</a>, <a href="qsqltablemodel.html">QSqlTableModel</a>, and <a href="qsqlrelationaltablemodel.html">QSqlRelationalTableModel</a>) that can be used with Qt's view classes, notably <a href="qtableview.html">QTableView</a>.</p>
<a name="general-overview"></a>
<h2>General Overview</h2>
<p>The Qt 4 SQL classes are divided into three layers:</p>
<ul>
<li>The database drivers</li>
<li>The core SQL classes</li>
<li>The GUI classes</li>
</ul>
<p>The database drivers and the core SQL classes are mostly the same as in Qt 3. The database item models are new with Qt 4; they inherit from <a href="qabstractitemmodel.html">QAbstractItemModel</a> and make it easy to present data from a database in a view class such as <a href="qlistview.html">QListView</a>, <a href="qtableview.html">QTableView</a>, and <a href="qtreeview.html">QTreeView</a>.</p>
<p>The philosophy behind the Qt 4 SQL module is that it should be possible to use database models for rendering and editing data just like any other item models. By changing the model at run-time, you can decide whether you want to store your data in an SQL database or in, say, an XML file. This generic approach has the additional benefit that you don't need to know anything about SQL to display and edit data.</p>
<p>The Qt 4 SQL module includes three item models:</p>
<ul>
<li><a href="qsqlquerymodel.html">QSqlQueryModel</a> is a read-only model based on an arbitrary SQL query.</li>
<li><a href="qsqltablemodel.html">QSqlTableModel</a> is a read-write model that works on a single table.</li>
<li><a href="qsqlrelationaltablemodel.html">QSqlRelationalTableModel</a> is a <a href="qsqltablemodel.html">QSqlTableModel</a> subclass with foreign key support.</li>
</ul>
<p>Combined with Qt's view classes and Qt's default delegate class (<a href="qitemdelegate.html">QItemDelegate</a>), the models offer a very powerful mechanism for accessing databases. For finer control on the rendering of the fields, you can subclass one of the predefined models, or even <a href="qabstractitemdelegate.html">QAbstractItemDelegate</a> or <a href="qitemdelegate.html">QItemDelegate</a> if you need finer control.</p>
<p>You can also perform some customizations without subclassing. For example, you can sort a table using <a href="qsqltablemodel.html#sort">QSqlTableModel::sort</a>(), and you can initialize new rows by connecting to the <a href="qsqltablemodel.html#primeInsert">QSqlTableModel::primeInsert</a>() signal.</p>
<p>One nice feature supported by the read-write models is the possibility to perform changes to the item model without affecting the database until <a href="qsqltablemodel.html#submitAll">QSqlTableModel::submitAll</a>() is called. Changes can be dropped using <a href="qsqltablemodel.html#revertAll">QSqlTableModel::revertAll</a>().</p>
<p>The new classes perform advantageously compared to the SQL module's GUI layer in Qt 3. Speed and memory improvements in the tool classes (especially <a href="qvariant.html">QVariant</a>, <a href="qstring.html">QString</a>, and <a href="qmap.html">QMap</a>) and in the SQL drivers contribute to making Qt 4 database applications more snappy.</p>
<p>See the <a href="qtsql.html">QtSql</a> module overview for a more complete introduction to Qt's SQL classes.</p>
<a name="example-code"></a>
<h2>Example Code</h2>
<p>The simplest way to present data from a database is to simply combine a <a href="qsqlquerymodel.html">QSqlQueryModel</a> with a <a href="qtableview.html">QTableView</a>:</p>
<pre> QSqlQueryModel model;
 model.setQuery(&quot;select * from person&quot;);

 QTableView view;
 view.setModel(&amp;model);
 view.show();</pre>
<p>To present the contents of a single table, we can use <a href="qsqltablemodel.html">QSqlTableModel</a> instead:</p>
<pre> QSqlTableModel model;
 model.setTable(&quot;person&quot;);
 model.select();

 QTableView view;
 view.setModel(&amp;model);
 view.show();</pre>
<p>In practice, it's common that we need to customize the rendering of a field in the database. In that case, we can create our own model based on <a href="qsqlquerymodel.html">QSqlQueryModel</a>. The next code snippet shows a custom model that prepends '#' to the value in field 0 and converts the value in field 2 to uppercase:</p>
<pre> class CustomSqlModel : public QSqlQueryModel
 {
     Q_OBJECT

 public:
     CustomSqlModel(QObject *parent = 0);

     QVariant data(const QModelIndex &amp;item, int role) const;
 };

 QVariant CustomSqlModel::data(const QModelIndex &amp;index, int role) const
 {
     QVariant value = QSqlQueryModel::data(index, role);
     if (value.isValid() &amp;&amp; role == Qt::DisplayRole) {
         if (index.column() == 0)
             return value.toString().prepend(&quot;#&quot;);
         else if (index.column() == 2)
             return value.toString().toUpper();
     }
     if (role == Qt::TextColorRole &amp;&amp; index.column() == 1)
         return qVariantFromValue(QColor(Qt::blue));
     return value;
 }</pre>
<p>It is also possible to subclass <a href="qsqlquerymodel.html">QSqlQueryModel</a> to add support for editing. This is done by reimplementing <a href="qabstractitemmodel.html#flags">QAbstractItemModel::flags</a>() to specify which database fields are editable and <a href="qabstractitemmodel.html#setData">QAbstractItemModel::setData</a>() to modify the database. Here's an example of a setData() reimplementation that changes the first or last name of a person:</p>
<pre> bool EditableSqlModel::setData(const QModelIndex &amp;index, const QVariant &amp;value, int <span class="comment">/* role */</span>)
 {
     if (index.column() &lt; 1 || index.column() &gt; 2)
         return false;

     QModelIndex primaryKeyIndex = QSqlQueryModel::index(index.row(), 0);
     int id = data(primaryKeyIndex).toInt();

     clear();

     bool ok;
     if (index.column() == 1) {
         ok = setFirstName(id, value.toString());
     } else {
         ok = setLastName(id, value.toString());
     }
     refresh();
     return ok;
 }</pre>
<p>It relies on helper functions called <tt>setFirstName()</tt> and <tt>setLastName()</tt>, which execute an <tt>update</tt>. Here's <tt>setFirstName()</tt>:</p>
<pre> bool EditableSqlModel::setFirstName(int personId, const QString &amp;firstName)
 {
     QSqlQuery query;
     query.prepare(&quot;update person set firstname = ? where id = ?&quot;);
     query.addBindValue(firstName);
     query.addBindValue(personId);
     return query.exec();
 }</pre>
<p>See Qt's <tt>examples/sql</tt> directory for more examples.</p>
<a name="comparison-with-qt-3"></a>
<h2>Comparison with Qt 3</h2>
<p>The core SQL database classes haven't changed so much since Qt 3. Here's a list of the main changes:</p>
<ul>
<li><a href="qsqldatabase.html">QSqlDatabase</a> is now value-based instead of pointer-based.</li>
<li><a href="porting4.html#qsqlfieldinfo">QSqlFieldInfo</a> and <a href="porting4.html#qsqlrecordinfo">QSqlRecordInfo</a> has been merged into <a href="qsqlfield.html">QSqlField</a> and <a href="qsqlrecord.html">QSqlRecord</a>.</li>
<li>The SQL query generation has been moved into the drivers. This makes it possible to use non-standard SQL extensions. It also opens the door to non-SQL databases.</li>
</ul>
<p>The GUI-related database classes have been entirely redesigned. The <a href="porting4.html#qsqlcursor">QSqlCursor</a> abstraction has been replaced with <a href="qsqlquerymodel.html">QSqlQueryModel</a> and <a href="qsqltablemodel.html">QSqlTableModel</a>; <a href="porting4.html#qsqleditorfactory">QSqlEditorFactory</a> is replaced by <a href="qabstractitemdelegate.html">QAbstractItemDelegate</a>; <a href="porting4.html#qdatatable">QDataTable</a> is replaced by <a href="qtableview.html">QTableView</a>. The old classes are part of the <a href="qt3support.html">Qt3Support</a> library to aid porting to Qt 4.</p>
<p>
[Previous: <a href="qt4-accessibility.html">Cross-Platform Accessibility Support in Qt 4</a>]
[<a href="qt4-intro.html">Home</a>]
[Next: <a href="qt4-network.html">The Network Module in Qt 4</a>]
</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
